package main

import (
	"encoding/json"
	"fmt"
	"os"
	"strconv"
	"strings"
)

var user_file string = "user.txt"
var user map[string]string = map[string]string{}
var car = make(map[string][][]string)

//存放用户信息
var user_lst = map[string]map[string]interface{}{}

//存放商品信息
var products = map[string]map[string]interface{}{
	"F001": {"name": "苹果", "price": 5},
	"F002": {"name": "香蕉", "price": 3},
	"F003": {"name": "葡萄", "price": 8},
	"F004": {"name": "榴莲", "price": 40},
}

//从文件中读取信息,初始化
func init_user() {
	content, err := os.ReadFile(user_file) //默认只读方式打开文件
	if err != nil {
		fmt.Println("初始化用户信息失败，没有指定文件")
	} else {
		err1 := json.Unmarshal(content, &user_lst)
		if err1 != nil {
			fmt.Println("json格式化失败，初始化用户信息失败")
		}
	}
}

func WriteUserInfo() {

	file, err := os.OpenFile(user_file, os.O_CREATE|os.O_WRONLY, 666)
	if err != nil {
		fmt.Println("打开文件写入用户信息失败")
	} else {
		str_m1, _ := json.Marshal(user_lst)
		file.Write(str_m1)
		fmt.Println("写入用户信息成功")
	}
}

func login(name string, passwd string) bool {
	if _, ok := user_lst[name]; ok && passwd == user_lst[name]["passwd"] {
		return true
	}
	return false
}

func regist(new_name string, new_passwd string) bool {
	if _, ok := user_lst[new_name]; ok {
		fmt.Println("注册失败！用户名已存在")
		return false
	} else {
		var new_money int
		fmt.Println("请输入充值金额：")
		fmt.Scanln(&new_money)
		var name_map = map[string]interface{}{
			"passwd": new_passwd,
			"money":  new_money,
		}
		user_lst[new_name] = name_map
		fmt.Println("将用户信息写入文件...")
		WriteUserInfo()
		return true
	}

}

func add_car(name string, product_id string, num string) {
	value := []string{product_id, num}
	car[name] = append(car[name], value)
	fmt.Println(car)
}

func checkout(name string) {
	m1 := int(user_lst[name]["money"].(float64))
	car_list := car[name]
	total := 0
	fmt.Println("编号  ", "名称  ", "单价", "数量", "总价")
	for _, pro := range car_list {
		pro_name := products[pro[0]]["name"]
		price := products[pro[0]]["price"].(int)
		num, _ := strconv.Atoi(pro[1])
		pro_total := price * num
		total += pro_total
		fmt.Println(pro[0], " ", pro_name, "  ", price, " ", pro[1], " ", pro_total)
	}
	fmt.Println("所有商品总价为：", total)
	if m1 >= total {
		m1 -= total
	} else {
		fmt.Println("余额不足！")
	}
	user_lst[name]["money"] = m1
	WriteUserInfo()
	fmt.Println(name, user_lst[name]["money"])
}

func menu() {
	fmt.Println(strings.Repeat("*", 20))
	fmt.Println("1、查看商品列表")
	fmt.Println("2、添加到购物车")
	fmt.Println("3、结算")
	fmt.Println("4、退出")

}

func show_goods() {
	fmt.Println("编号", strings.Repeat(" ", 10), "名称", strings.Repeat(" ", 10), "价格")
	for k, _ := range products {
		fmt.Println(k, strings.Repeat(" ", 10), products[k]["name"], strings.Repeat(" ", 10), products[k]["price"])
	}
}

func main() {
	init_user()
	fmt.Println(strings.Repeat("*", 25) + "欢迎来到三乐购物系统" + strings.Repeat("*", 25))
	flag := 0
	for flag == 0 {
		fmt.Println("1.登录")
		fmt.Println("2.注册")
		fmt.Println("请输入你的选择(按q退出)：")
		var options, name, passwd, new_name, new_passwd, op, product_id, num string
		fmt.Scanln(&options)
		switch options {
		case "1":
			fmt.Println("请输入用户名:")
			fmt.Scanln(&name)
			fmt.Println("请输入密码:")
			fmt.Scanln(&passwd)
			if login(name, passwd) {
				fmt.Println("登录成功！")
				for true {
					menu()
					fmt.Println("请输入你的操作:")
					fmt.Scanln(&op)
					if op == "1" {
						show_goods()
					} else if op == "2" {
						fmt.Println("请输入添加到购物车的商品编号：")
						fmt.Scanln(&product_id)
						if _, ok := products[product_id]; ok {
							fmt.Println("请输入需要购买的数量:")
							fmt.Scanln(&num)
							add_car(name, product_id, num)
						}
					} else if op == "3" {
						checkout(name)
					} else if op == "4" {
						break
					}
				}
			} else {
				fmt.Println("登录失败！用户名或密码错误")
			}
		case "2":
			fmt.Println("请输入用户名:")
			fmt.Scanln(&new_name)
			fmt.Println("请输入密码:")
			fmt.Scanln(&new_passwd)
			if regist(new_name, new_passwd) {
				fmt.Println(user_lst)
				fmt.Println("注册成功！")
			}
		case "q":
			flag = 1
			break

		}
	}
}
